package com.mao.dao.warehouse;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.mao.dao.BaseDAOHibernate;
import com.mao.model.product.Product;
import com.mao.model.product.ProductClass;
import com.mao.model.warehouse.WareHouseClass;

@Component("wareHouseClassDao")
public class WareHouseClassDao extends BaseDAOHibernate {
	public List<WareHouseClass> getAllWareHouseClass(Long storeid) {
		Session session = this.getSession();
		String hql = "from WareHouseClass t where t.parent.id is null and t.status = "
				+ WareHouseClass.STATUS_NORMAL + " and t.store.id=" + storeid;
		Query query = session.createQuery(hql);
		return query.list();
	}

	public List<WareHouseClass> getAllWareHouseClass(){
		Session session = this.getSession();
		String hql = "from WareHouseClass";
		Query query = session.createQuery(hql);
		return query.list();
	}
	
	public WareHouseClass saveWareHouseClass(WareHouseClass wc) {
		getHibernateTemplate().save(wc);
		return wc;
	}

	public WareHouseClass updateWareHouseClass(WareHouseClass wc) {
		getHibernateTemplate().merge(wc);
		return wc;
	}

	public WareHouseClass getWareHouseClassById(long id) {
		Session session = this.getSession();
		String hql = "From WareHouseClass wc where wc.status=:status and wc.id=:id";
		Query query = session.createQuery(hql);
		query.setParameter("status", WareHouseClass.STATUS_NORMAL);
		query.setParameter("id", id);
		List<WareHouseClass> list = query.list();
		if (list.size() > 0) {
			WareHouseClass whc = list.get(0);
			Hibernate.initialize(whc.getLowClass());
			return whc;
		}
		return null;
	}

	public String valDelWHClass(long id) {
		// 返回1表示该分类下已有分类 2表示该分类下已有商品信息
		Session session = this.getSession();
		String hql = "From WareHouseClass pc where pc.status=:status and pc.id=:id";
		Query query = session.createQuery(hql);
		query.setParameter("status", ProductClass.STATUS_NORMAL);
		query.setParameter("id", id);
		List<WareHouseClass> list = query.list();
		WareHouseClass pcRes = null;
		if (list.size() > 0) {
			pcRes = list.get(0);
			if (!Hibernate.isInitialized(pcRes.getLowClass())) {
				Hibernate.initialize(pcRes.getLowClass());
			}
			if (pcRes.getLowClass().size() > 0) {
				return "1";
			}
		}
		Session psession = this.getSession();
		String phql = "From WareHouse p where p.status=:status and p.wc.id=:id";
		Query pquery = psession.createQuery(phql);
		pquery.setParameter("status", ProductClass.STATUS_NORMAL);
		pquery.setParameter("id", id);
		List<Product> plist = pquery.list();
		if (plist.size() > 0) {
			return "2";
		}
		return "0";
	}
}
